using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }

    [Header("UI引用")]
    [SerializeField] private GameBoard gameBoard;
    [SerializeField] private UIManager uiManager;

    private long userId;
    private string username;
    private int score;
    private int winCount;
    private int loseCount;
    
    private string currentGameId;
    private PieceColor myColor;
    private PieceColor currentTurn;
    private long currentPlayerId;

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
            return;
        }
    }

    private void Start()
    {
        RegisterNetworkCallbacks();
    }

    private void RegisterNetworkCallbacks()
    {
        NetworkManager.Instance.OnLoginResponse += HandleLoginResponse;
        NetworkManager.Instance.OnMatchResponse += HandleMatchResponse;
        NetworkManager.Instance.OnMatchSuccess += HandleMatchSuccess;
        NetworkManager.Instance.OnGameStart += HandleGameStart;
        NetworkManager.Instance.OnPlacePieceResponse += HandlePlacePieceResponse;
        NetworkManager.Instance.OnGameOver += HandleGameOver;
        NetworkManager.Instance.OnError += HandleError;
    }

    private void OnDestroy()
    {
        if (NetworkManager.Instance != null)
        {
            NetworkManager.Instance.OnLoginResponse -= HandleLoginResponse;
            NetworkManager.Instance.OnMatchResponse -= HandleMatchResponse;
            NetworkManager.Instance.OnMatchSuccess -= HandleMatchSuccess;
            NetworkManager.Instance.OnGameStart -= HandleGameStart;
            NetworkManager.Instance.OnPlacePieceResponse -= HandlePlacePieceResponse;
            NetworkManager.Instance.OnGameOver -= HandleGameOver;
            NetworkManager.Instance.OnError -= HandleError;
        }
    }

    // 登录
    public void Login(string username, string password)
    {
        NetworkManager.Instance.Login(username, password);
    }

    private void HandleLoginResponse(LoginResponse response)
    {
        if (response.Success)
        {
            userId = response.UserId;
            username = response.Username;
            score = response.Score;
            winCount = response.WinCount;
            loseCount = response.LoseCount;

            Debug.Log($"登录成功: {username}, 积分: {score}");
            uiManager.ShowMessage($"欢迎, {username}!");
            uiManager.UpdateUserInfo(username, score, winCount, loseCount);
            uiManager.ShowMainMenu();
        }
        else
        {
            Debug.LogError($"登录失败: {response.Message}");
            uiManager.ShowMessage(response.Message);
        }
    }

    // 匹配
    public void RequestMatch()
    {
        NetworkManager.Instance.RequestMatch();
    }

    private void HandleMatchResponse(MatchResponse response)
    {
        if (response.Success)
        {
            Debug.Log("已加入匹配队列");
            uiManager.ShowMessage("正在匹配...");
            uiManager.ShowMatchingUI();
        }
        else
        {
            Debug.LogWarning(response.Message);
            uiManager.ShowMessage(response.Message);
        }
    }

    public void CancelMatch()
    {
        NetworkManager.Instance.CancelMatch();
        uiManager.ShowMainMenu();
    }

    private void HandleMatchSuccess(MatchSuccess matchSuccess)
    {
        Debug.Log($"匹配成功! 游戏ID: {matchSuccess.GameId}");
        
        currentGameId = matchSuccess.GameId;
        myColor = matchSuccess.YourColor;

        string opponentName = myColor == PieceColor.Black ? 
            matchSuccess.WhitePlayerName : matchSuccess.BlackPlayerName;

        uiManager.ShowMessage($"匹配成功! 对手: {opponentName}");
        uiManager.ShowGameUI();
        
        gameBoard.SetGameInfo(currentGameId, userId, myColor);
        gameBoard.ResetBoard();

        string colorText = myColor == PieceColor.Black ? "黑方" : "白方";
        uiManager.UpdateGameInfo($"你是{colorText}", opponentName);
    }

    private void HandleGameStart(GameStart gameStart)
    {
        Debug.Log("游戏开始!");
        currentTurn = gameStart.CurrentTurn;
        currentPlayerId = gameStart.CurrentPlayerId;

        bool isMyTurn = currentPlayerId == userId;
        gameBoard.SetMyTurn(isMyTurn);
        
        string turnText = isMyTurn ? "你的回合" : "对手回合";
        uiManager.UpdateTurnInfo(turnText);
    }

    private void HandlePlacePieceResponse(PlacePieceResponse response)
    {
        if (response.Success)
        {
            // 在棋盘上放置棋子
            gameBoard.PlacePiece(response.Row, response.Col, response.Color);

            // 更新回合信息
            if (response.NextPlayerId != 0)
            {
                currentTurn = response.NextTurn;
                currentPlayerId = response.NextPlayerId;
                
                bool isMyTurn = currentPlayerId == userId;
                gameBoard.SetMyTurn(isMyTurn);
                
                string turnText = isMyTurn ? "你的回合" : "对手回合";
                uiManager.UpdateTurnInfo(turnText);
            }
        }
        else
        {
            Debug.LogWarning($"落子失败: {response.Message}");
            uiManager.ShowMessage(response.Message);
        }
    }

    private void HandleGameOver(GameOverSync gameOver)
    {
        Debug.Log($"游戏结束! 结果: {gameOver.Result}");

        // 高亮获胜位置
        if (gameOver.WinPositions.Count > 0)
        {
            List<WinPosition> positions = new List<WinPosition>(gameOver.WinPositions);
            gameBoard.HighlightWinPositions(positions);
        }

        // 显示结果
        string resultText = GetGameResultText(gameOver);
        uiManager.ShowGameOverDialog(resultText);

        gameBoard.SetMyTurn(false);
    }

    private string GetGameResultText(GameOverSync gameOver)
    {
        bool isWinner = gameOver.WinnerId == userId;
        
        switch (gameOver.Result)
        {
            case GameResult.BlackWin:
            case GameResult.WhiteWin:
                return isWinner ? "你赢了!" : $"你输了! 获胜者: {gameOver.WinnerName}";
            case GameResult.Draw:
                return "平局!";
            case GameResult.SurrenderResult:
                return isWinner ? "对手投降，你赢了!" : "你投降了!";
            default:
                return "游戏结束";
        }
    }

    public void Surrender()
    {
        NetworkManager.Instance.Surrender();
    }

    public void BackToMainMenu()
    {
        gameBoard.ResetBoard();
        currentGameId = null;
        uiManager.ShowMainMenu();
    }

    private void HandleError(ErrorMessage error)
    {
        Debug.LogError($"错误 [{error.Code}]: {error.Message}");
        uiManager.ShowMessage($"错误: {error.Message}");
    }
}
